package cn.cmkj.auction.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.util.LogUtil;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import cn.cmkj.auction.R;
import cn.cmkj.auction.adapter.AuctionOrderListAdapter;
import cn.cmkj.auction.app.Urls;
import cn.cmkj.auction.data.db.User;
import cn.cmkj.auction.data.http.AuctionOrder;
import cn.cmkj.auction.ui.OrderAuctionDetailActivity;
import cn.cmkj.auction.utils.HttpCallback;
import cn.cmkj.auction.utils.ItemClickSupport;
import cn.cmkj.auction.widget.swipeRecyclerView.MySwipeMenuRecyclerView;

/**
 * Created by cunguoyao on 2018/4/23.
 */
@ContentView(R.layout.fragment_main_paimai_list)
public class MyPaimaiFragment extends BaseFragment implements MySwipeMenuRecyclerView.OnLoadListener {

    private View view;
    @ViewInject(R.id.swipeRecyclerView)
    private MySwipeMenuRecyclerView swipeRecyclerView;

    private List<AuctionOrder> mData;
    private AuctionOrderListAdapter auctionListAdapter;
    private boolean requesting = false;
    private int page = 1;
    private int type;//1定金订单 2拍卖订单

    public static MyPaimaiFragment create(int type) {
        MyPaimaiFragment f = new MyPaimaiFragment();
        Bundle args = new Bundle();
        args.putInt("type", type);
        f.setArguments(args);
        return f;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        type = getArguments().getInt("type", 1);
        mData = new ArrayList<>();
        auctionListAdapter = new AuctionOrderListAdapter(getActivity(), mData);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if(view == null) {
            view = x.view().inject(this, inflater, container);
        }
        swipeRecyclerView.getRecyclerView().setLayoutManager(new GridLayoutManager(getActivity(), 1));
        //((SwipeMenuRecyclerView)swipeRecyclerView.getRecyclerView()).setLongPressDragEnabled(true); // 开启拖拽。
        //((SwipeMenuRecyclerView)swipeRecyclerView.getRecyclerView()).setItemViewSwipeEnabled(true); // 开启滑动删除。
        swipeRecyclerView.setAdapter(auctionListAdapter);
        ItemClickSupport.addTo(swipeRecyclerView.getRecyclerView()).setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
            @Override
            public void onItemClicked(RecyclerView recyclerView, View itemView, int position) {
                AuctionOrder item = auctionListAdapter.getItem(position);
                Intent intent = new Intent(getActivity(), OrderAuctionDetailActivity.class);
                if(type == 1) {
                    intent.putExtra(OrderAuctionDetailActivity.FROM, OrderAuctionDetailActivity.FROM_ORDER_LIST_DJ);
                }else {
                    intent.putExtra(OrderAuctionDetailActivity.FROM, OrderAuctionDetailActivity.FROM_ORDER_LIST_PM);
                }
                intent.putExtra("order", item);
                startActivity(intent);
            }
        });
        swipeRecyclerView.setOnLoadListener(this);
        swipeRecyclerView.setRefreshing(true);
        return view;
    }

    @Override
    public void onRefresh() {
        if(!requesting) {
            page = 1;
            mData.clear();
            auctionListAdapter.notifyDataSetChanged();
            fetchData();
        }
    }

    @Override
    public void onLoadMore() {
        if(!requesting) {
            page = page +1;
            LogUtil.e("--onLoadMore:page=" + page);
            fetchData();
        }
    }

    public void fetchData() {
        requesting = true;
        User user = getAccount();
        if(user == null) {
            showLoginDialog(getActivity());
        }else {
            RequestParams params = new RequestParams(Urls.api);
            params.addParameter("method", Urls.auctionOrderList);
            params.addParameter("accesstoken", user.getToken());
            params.addParameter("member_id", user.getId());
            params.addParameter("type", String.valueOf(type));
            params.addParameter("page_no", page);
            params.addParameter("page_size", Urls.pageSize);
            x.http().request(HttpMethod.POST, params, new HttpCallback(getActivity()) {
                @Override
                public void success(String s) {
                    swipeRecyclerView.complete();
                    requesting = false;
                    if(page == 1) mData.clear();
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(s);
                        JSONObject json = jsonObject.optJSONObject("data");
                        JSONArray jsonArray = json.optJSONArray("data");
                        List<AuctionOrder> temp = AuctionOrder.parseFromJsonArray(jsonArray);
                        mData.addAll(temp);
                        auctionListAdapter.notifyDataSetChanged();
                        if(Urls.pageSize > temp.size()) {
                            swipeRecyclerView.setLoadMoreEnable(false);
                        }else {
                            swipeRecyclerView.setLoadMoreEnable(true);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void error(Throwable ex, String msg, boolean isOnCallback) {
                    swipeRecyclerView.complete();
                    requesting = false;
                    if(ex != null)ex.printStackTrace();
                    LogUtil.e("---onError-----" + "onError");
                    Toast.makeText(getActivity(), TextUtils.isEmpty(msg) ? "请求失败" : msg, Toast.LENGTH_SHORT).show();
                }

                @Override
                public void cancel(CancelledException e) {
                    swipeRecyclerView.complete();
                    requesting = false;
                }

                @Override
                public void finished() {
                    requesting = false;
                    swipeRecyclerView.complete();
                }
            });
        }
    }
}
